package com.googlecode.microanalyst.palette.edit;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.AccessibleEditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;

import com.googlecode.microanalyst.designer.edit.AnalysisEditPart;
import com.googlecode.microanalyst.palette.figure.DatasetFigure;
import com.googlecode.microanalyst.palette.i18n.PaletteMessages;
import com.googlecode.microanalyst.palette.model.Dataset;
import com.googlecode.microanalyst.palette.model.DatasetProperties;

public class DatasetEditor extends AnalysisEditPart {

	public DatasetEditor() {
	}

	@Override
	protected AccessibleEditPart createAccessible() {
		return new AccessibleGraphicalEditPart() {
			public void getValue(AccessibleControlEvent e) {
				e.result = getDataset().getName();
			}

			public void getName(AccessibleEvent e) {
				e.result = PaletteMessages.Palette_Tool_Dataset;
			}
		};
	}

	protected Dataset getDataset() {
		return (Dataset) getModel();
	}

	@Override
	protected IFigure createFigure() {
		DatasetFigure figure = new DatasetFigure();
		return figure;
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
		//installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, null);
		installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE,
				new DatasetDirectEditPolicy());
		installEditPolicy(EditPolicy.COMPONENT_ROLE, new DatasetEditPolicy());
	}

	private void performDirectEdit() {
		DatasetFigure f = (DatasetFigure) getFigure();
		DatasetCellEditorLocator cel = new DatasetCellEditorLocator(f);
		DatasetEditManager em = new DatasetEditManager(this, cel);
		em.show();
	}

	public void performRequest(Request request) {
		if (request.getType() == RequestConstants.REQ_DIRECT_EDIT)
			performDirectEdit();
	}

	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equalsIgnoreCase(DatasetProperties.PROPERTY_NAME))
			refreshVisuals();
		else
			super.propertyChange(evt);
	}

	protected void refreshVisuals() {
		((DatasetFigure) getFigure()).setText(getDataset().getName());
		super.refreshVisuals();
	}

}
